package com.jy.api.service.impl;import com.alibaba.fastjson.JSON;import com.jy.api.controller.admin.params.InventoryFlowRequest;import com.jy.api.controller.admin.params.MatchProductEditParams;import com.jy.api.dao.*;import com.jy.api.domain.*;import com.jy.api.exception.MyException;import com.jy.api.service.*;import com.jy.api.signUpReq.*;import com.jy.api.signUpReq.MarsCallReq.GiftReq;import com.jy.api.signUpReq.MarsCallReq.SalesProductRes;import com.jy.api.signUpReq.admin.ProductSignUpReq;import com.jy.api.signUpReq.admin.ShowEnabledAndPurchaseReq;import com.jy.api.signUpReq.admin.UpdateProductTimeSlot;import com.jy.api.signUpReq.stock.BarAssembleReq;import com.jy.api.signUpReq.stock.BarCheckReq;import com.jy.api.signUpReq.stock.StockBarReq;import com.jy.api.util.*;import com.jy.api.util.Result;import com.jy.api.vo.admin.payment.PaymentVo;import com.jy.api.vo.pos.WorkShift.WorkShiftVo;import com.jy.api.vo.pos.index.IndexVo;import com.jy.api.vo.pos.index.ProductVo;import com.jy.api.vo.pos.productInVo.ProductInVo;import com.jy.api.vo.stock.HomePageVo;import com.jy.api.vo.stock.StockProductVo;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang3.StringUtils;import org.json.JSONException;import org.json.JSONObject;import org.springframework.beans.BeanUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.domain.Page;import org.springframework.data.domain.PageRequest;import org.springframework.data.domain.Pageable;import org.springframework.data.domain.Sort;import org.springframework.data.jpa.domain.Specification;import org.springframework.http.ResponseEntity;import org.springframework.jdbc.core.BeanPropertyRowMapper;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import org.springframework.web.client.RestTemplate;import reactor.core.support.UUIDUtils;import javax.annotation.Resource;import javax.persistence.criteria.CriteriaBuilder;import javax.persistence.criteria.Predicate;import java.math.BigDecimal;import java.text.ParseException;import java.text.SimpleDateFormat;import java.time.LocalDateTime;import java.time.format.DateTimeFormatter;import java.util.*;import java.util.stream.Collectors;@Slf4j@Service@Transactionalpublic class ProductServiceImpl implements ProductService {    @Autowired    ProductDao productDao;    @Autowired    ProductTypeService productTypeService;    @Autowired    InventoryUrlUtil urlUtil;    @Autowired    RestTemplate restTemplate;    @Autowired    OpenSearchService openSearchService;    @Autowired    private StockTransactionService transactionService;    @Autowired    private StoreDao storeDao;    @Autowired    private EmployeeDao employeeDao;    @Autowired    private StockTransactionDao transactionDao;    @Autowired    private StockCheckOrderDao checkOrderDao;    @Autowired    WorkShiftDao workShiftDao;    @Autowired    private ProductTypeDao productTypeDao;    @Autowired    WorkshiftServiceImpl workshiftService;    @Autowired    private PaymentService paymentService;    @Autowired    private OrderDao orderDao;    private JdbcTemplate jdbc;    @Autowired    private InventoryDao inventoryDao;    @Autowired    private RedisSyncLocker redisSyncLocker;    @Autowired    private StockTransactionDao stockTransactionDao;    @Autowired    private ProductSalesDao productSalesDao;    @Autowired    private EmployeeCommissionDao commissionDao;    @Autowired    private StockService stockService;    @Autowired    private ProductMaterialDao productMaterialDao;    @Autowired    private EmployeePostCommissionDao employeePostCommissionDao;    @Autowired    private ProductTransactionDao productTransactionDao;    @Autowired    private EmployeeGroupDao employeeGroupDao;    @Autowired    private OrderItemDao orderItemDao;    @Autowired    private ProductSpecDao productSpecDao;    @Autowired    StockTransactionService stockTransactionService;    @Autowired    public void setJdbc(JdbcTemplate jdbc) {        this.jdbc = jdbc;    }    @Transactional    public Product saveOrUpdate(ProductSignUpReq productSignUpReq, ProductType productType) {        Product producat = productDao.findOne(productSignUpReq.getId());        ProductSales productSales = productSalesDao.findByProductId(productSignUpReq.getId());        if (productSales == null) {            productSales = new ProductSales();            productSales.setProductName(productSignUpReq.getName());            productSales.setStoreId(productSignUpReq.getStoreId());            productSales.setProductId(productSignUpReq.getId());            productSales.setCount(productSignUpReq.getSalesCount());            productSalesDao.save(productSales);        } else {            productSales.setProductName(productSignUpReq.getName());            productSales.setCount(productSignUpReq.getSalesCount());            productSalesDao.save(productSales);        }        if (producat == null) {            producat = new Product();        }        if (!StringUtils.isBlank(productSignUpReq.getId()) || (producat.getSalesPrice() != productSignUpReq.getSalesPrice() || productSignUpReq.isOpenTimeEnabled() || productSignUpReq.isPostEnabled() || producat.getCommission() != productSignUpReq.getCommission())) {            ProductTransaction transaction = new ProductTransaction();            transaction.setProductName(productSignUpReq.getName());            transaction.setStoreId(productSignUpReq.getStoreId());            StringBuilder stringBuffer = new StringBuilder();            stringBuffer.append(productSignUpReq.getLoginName()).append("在").append(MyDateUtils.dtSimpleFormatHour(new Date())).append("修改了商品\n");            if (producat.getSalesPrice() != productSignUpReq.getSalesPrice()) {                stringBuffer.append("商品售价为:" + "变动前" + producat.getSalesPrice() + "元\n" + "变动后" + productSignUpReq.getSalesPrice() + "元\n");            }            if (productSignUpReq.isOpenTimeEnabled()) {                stringBuffer.append("开启了时间段折扣，分别为：\n");                for (ProductSignUpReq.EmployeeCommissionItems item : productSignUpReq.getItems()) {                    stringBuffer.append("开始时间为").append(item.getBegin()).append("结束时间为").append(item.getEnd()).append("提成金额为").append(item.getCommission()).append("元\n");                }            }            if (productSignUpReq.isPostEnabled()) {                stringBuffer.append("开启了岗位折扣，分别为：\n");                for (ProductSignUpReq.EmployeePostCommissionParams postParam : productSignUpReq.getPostParams()) {                    EmployeeGroup employeeGroup = employeeGroupDao.findOne(postParam.getGroupId());                    if (employeeGroup != null) {                        stringBuffer.append("岗位名称为").append(employeeGroup.getName()).append("提成金额为").append(postParam.getCommission()).append("元\n");                    }                }            }            if (producat.getCommission() != productSignUpReq.getCommission()) {                stringBuffer.append("固定提成为:" + "变动前" + producat.getCommission() + "元\n" + "变动后" + productSignUpReq.getCommission() + "元\n");            }            transaction.setProductId(productSignUpReq.getId());            transaction.setNotice(stringBuffer.toString());            productTransactionDao.save(transaction);        }        BeanUtils.copyProperties(productSignUpReq, producat);        producat.setSort(productSignUpReq.getSort());        producat.setWeek(productSignUpReq.getWeek());        producat.setPinyin(PinYinUtil.getFirstSpell(producat.getName()));        producat.setOpenMatchEnabled(productSignUpReq.isOpenMatchEnabled());        producat.setProductType(productType);        producat.setSpecs(productSignUpReq.getSpecs());        producat.setProductStatus(producat.getProductStatus());        producat.setProductQty(productSignUpReq.getProductQty());        producat.setPort(productSignUpReq.getPort());        producat.setIpName(productSignUpReq.getIpName());        producat.setIpAddress(productSignUpReq.getIpAddress());        producat.setIpId(productSignUpReq.getIpId());        producat.setThreshold(productSignUpReq.getThreshold());        producat.setNote(productSignUpReq.getNote());        List<ProductSpec> productSpecs = productSpecDao.findAllByIdIn(productSignUpReq.getSpecIds());        if (null == producat.getProductSpecs()) {            producat.setProductSpecs(new HashSet<>());        }        producat.getProductSpecs().clear();        if (productSpecs.size() > 0) {            producat.getProductSpecs().addAll(productSpecs);        }        if (productSignUpReq.isOpenTimeEnabled()) {            List<EmployeeCommission> list = new ArrayList<>();            for (ProductSignUpReq.EmployeeCommissionItems items : productSignUpReq.getItems()) {                EmployeeCommission employeeCommission = new EmployeeCommission(items);                list.add(employeeCommission);            }            if (null != producat.getCommissions()) {                producat.getCommissions().clear();                producat.getCommissions().addAll(list);            } else {                producat.setCommissions(list);            }        }        if (producat.isPostEnabled()) {            producat.setOpenTimeEnabled(false);        }        Product product = productDao.save(producat);        ProductType type = productTypeDao.findOne(product.getProductType().getId());        if (null == type.getParent()) {            product.setTypeName(type.getName());            product.setParentTypeName(type.getName());        } else {            if (StringUtils.isNotBlank(type.getParent().getName())) {                product.setParentTypeName(type.getParent().getName());            } else {                product.setParentTypeName(type.getName());            }            product.setTypeName(type.getName());        }        product.setHaveMatchProductEnabled(!product.getProductId().isEmpty());        if (productSignUpReq.isPostEnabled()) {            product.getPostCommissions().clear();            for (ProductSignUpReq.EmployeePostCommissionParams postParam : productSignUpReq.getPostParams()) {                EmployeePostCommission commission = new EmployeePostCommission();                BeanUtils.copyProperties(postParam, commission);                product.getPostCommissions().add(commission);            }        }        productDao.save(product);        List<Inventory> list = inventoryDao.findByEnabledAndProductId(true, productSignUpReq.getId());        List<Inventory> inventoryList = new ArrayList<>();        for (Inventory in : list) {            in.setName(product.getName());            inventoryList.add(in);        }        inventoryDao.save(inventoryList);        if (null != productSignUpReq.getStoreIds() && !productSignUpReq.getStoreIds().isEmpty()) {            List<Product> products = new ArrayList<>();            for (String storeId : productSignUpReq.getStoreIds()) {                //查询这个商品在不在，不在加（1），在就正常创建商品                Store store = storeDao.findOne(storeId);                if (store == null) {                    throw new MyException("选择中含有不存在的店铺，请核实后进行操作" + storeId);                }                Product product1 = productDao.findTop1ByStoreIdAndNameAndEnabledIsTrue(storeId, product.getName());                Product product2 = new Product();                BeanUtils.copyProperties(producat, product2);                product2.setId(UuidUtil.getUuid());                product2.setStoreId(storeId);                if (null != product2.getProductSpecs() && !product2.getProductSpecs().isEmpty()) {                    product2.getProductSpecs().clear();                }                if (null != product2.getSpecs() && !product2.getSpecs().isEmpty()) {                    product2.getSpecs().clear();                }                if (null != product2.getProductMaterialItems() && !product2.getProductMaterialItems().isEmpty()) {                    product2.getProductMaterialItems().clear();                }                if (null != product2.getProductId() && !product2.getProductId().isEmpty()) {                    product2.getProductId().clear();                }                if (null != product2.getPostCommissions() && !product2.getPostCommissions().isEmpty()) {                    product2.getPostCommissions().clear();                }                if (product1 != null) {                    product2.setName(product.getName() + "(1)");                }                ProductType firstType = productTypeDao.findByStoreIdAndName(storeId, product.getProductType().getName());                if (firstType == null) {                    throw new MyException(store.getName() + ":店铺不存在该二级分类" + product.getProductType().getName() + "，商品无法同步，请去该店铺建立相同类名");                }                if (null != firstType.getParent()) {                    ProductType secondType = productTypeDao.findByStoreIdAndName(storeId, product.getProductType().getName());                    if (secondType == null) {                        throw new MyException(store.getName() + ":店铺不存在该一级分类" + product.getProductType().getName() + "，商品无法同步，请去该店铺建立相同类名");                    }                }                product2.setProductType(firstType);                product2.setTypeName(firstType.getName());                if (null != firstType.getParent()) {                    product2.setParentTypeName(firstType.getParent().getName());                } else {                    product2.setParentTypeName(firstType.getName());                }                products.add(product2);            }            productDao.save(products);        }        return product;    }    @Override    public Product matchProductEdit(MatchProductEditParams req, ProductType productType) throws MyException {        Product product;        if (!StringUtils.isBlank(req.getId())) {            product = productDao.findOne(req.getId());            if (product == null) {                throw new MyException("商品不存在");            }        } else {            product = new Product();            product.setId(UuidUtil.getUuid());        }        product.setName(req.getName());        product.setSalesPrice(req.getSalesPrice());        product.setProductType(productType);        product.setStockEnabled(req.isStockEnabled());        product.setStoreId(req.getStoreId());        product.setPinyin(PinYinUtil.getFirstSpell(product.getName()));        product.setMatchProductEnabled(true);        ProductType type = productTypeDao.findOne(product.getProductType().getId());        if (null == type.getParent()) {            product.setTypeName(type.getName());            product.setParentTypeName(type.getName());        } else {            product.setParentTypeName(type.getParent().getName());            product.setTypeName(type.getName());        }        productDao.save(product);        return product;    }    @Override    public Result addMatchToProduct(MatchProductEditParams req, Product product) {        product.getProductId().clear();        for (String productId : req.getProductIds()) {            Product matchProduct = productDao.findOne(productId);            if (matchProduct == null) {                return new Result(400, "配品不存在，请核实");            }            product.getProductId().add(productId);        }        product.setHaveMatchProductEnabled(!product.getProductId().isEmpty());        return new Result(200, "保存成功");    }    @Override    public List<SalesProductRes> getSalesProduct(String storeId, Pageable pageable) {        Page<Product> products = productDao.findAllByStoreIdAndSalesEnabledAndEnabledOrderBySortDesc(storeId, true, true, pageable);        List<SalesProductRes> res = new ArrayList<>();        List<String> integers = new ArrayList<>();        Map map = new HashMap();        for (Product product : products) {            integers.add(product.getId());            map.put(product.getId(), product);        }        List<ProductSales> productSales = productSalesDao.findAllByProductIdIn(integers);        for (ProductSales productSale : productSales) {            Product product = (Product) map.get(productSale.getProductId());            SalesProductRes salesProductRes = new SalesProductRes();            if (product.isSalesShowEnabled()) {                int count = productSale.getCount();                salesProductRes.setCount(count);            }            salesProductRes.setPrice(product.getSalesPrice());            salesProductRes.setProductName(product.getName());            salesProductRes.setImage(product.getImageURL());            salesProductRes.setSort(product.getSort());            res.add(salesProductRes);        }        return res.stream().sorted(Comparator.comparing(SalesProductRes::getSort).reversed()).collect(Collectors.toList());    }    @Override    public List<String> judgeProductQty(String orderId) {        Order order = orderDao.findOne(orderId);        List<String> strings = new ArrayList<>();        for (OrderItem item : order.getItems()) {            Product product = productDao.findOne(item.getProductId());            if (product.isStockEnabled()) {                int surplus = stockTransactionService.surplus(product.getStoreId(), product.getId(), 1, StockLevel.BAR);                if ((surplus - item.getQuantity()) < 0) {                    strings.add(product.getName());                }            }        }        return strings;    }    public Map<String, String> getProductImages(List<String> productIds) {        Map<String, String> map = new HashMap<>();        if (productIds.size() > 0) {            List<Product> products = productDao.findListByIdIn(productIds);            for (Product product : products) {                map.put(product.getId(), product.getImageURL());            }        }        return map;    }    @Override    public Map<String, IndexVo> setProducts(List<Product> products) {        Map<String, IndexVo> indexVoMap = new HashMap<>();        for (Product product : products) {            ProductVo productVo = new ProductVo(product);            IndexVo indexVo = new IndexVo(product.getProductType().getId(),                    product.getProductType().getName(), product.getProductType().getSequence());            if (product.getProductType().getParent() == null) {                if (!product.getProductType().isEnabled()) {                    continue;                }                //自己是主分类                IndexVo indexVo1 = indexVoMap.get(product.getProductType().getId());                if (indexVo1 == null) {                    indexVo.getProducts().add(productVo);                    indexVoMap.put(indexVo.getTypeId(), indexVo);                } else {                    indexVo1.getProducts().add(productVo);                }            } else {                //自己是子分类                IndexVo indexVo1 = indexVoMap.get(product.getProductType().getParent().getId());                if (indexVo1 == null) {                    if (!product.getProductType().getParent().isEnabled()) {                        continue;                    }                    IndexVo indexVo2 = new IndexVo(product.getProductType().getParent().getId(),                            product.getProductType().getParent().getName(), product.getProductType()                            .getParent().getSequence());                    indexVo.getProducts().add(productVo);                    indexVo2.getSubTypes().add(indexVo);                    indexVoMap.put(indexVo2.getTypeId(), indexVo2);                } else {                    //主分类存在                    Boolean check = false;                    //判断子分类是否存在                    for (IndexVo indexVo2 : indexVo1.getSubTypes()) {                        if (StringUtils.equals(indexVo2.getTypeId(), indexVo.getTypeId())) {                            indexVo2.getProducts().add(productVo);                            check = true;                            break;                        }                    }                    //子分类不存在                    if (!check) {                        indexVo.getProducts().add(productVo);                        indexVo1.getSubTypes().add(indexVo);                    }                }            }        }        return indexVoMap;    }    @Override    @Transactional    public void cloneProduct(CloneProductSignUpReq cloneProductSignUpReq) {        //优先克隆商品分类        Map<String, Map<String, ProductType>> mapMap = productTypeService.cloneType(cloneProductSignUpReq);        Map<String, ProductType> oneMap = mapMap.get("one");        Map<String, ProductType> twoMap = mapMap.get("two");        //把有资料的店铺查询出来        List<Product> products = productDao.findByStoreId(cloneProductSignUpReq.getParentStoreId());        List<Product> products1 = new ArrayList<>();        for (Product product : products) {            Product product1 = new Product();            BeanUtils.copyProperties(product, product1);            ProductType type = null;            if (product1.getProductType().getParent() != null) {                type = twoMap.get(product1.getProductType().getId());            } else {                type = oneMap.get(product1.getProductType().getId());            }            product1.setId(UuidUtil.getUuid());            product1.setQuantity(0);            product1.setStoreId(cloneProductSignUpReq.getStoreId());            product1.setProductType(type);            product1.setSalesCount(0);            product1.setProductId(new ArrayList<>());            product1.setProductMaterialItems(null);            product1.setCommissions(null);            product1.setPostCommissions(null);            ProductSales productSales = productSalesDao.findByProductId(product1.getId());            if (productSales == null) {                productSales = new ProductSales();                productSales.setProductName(product1.getName());                productSales.setStoreId(product1.getStoreId());                productSales.setProductId(product1.getId());                productSales.setCount(product1.getSalesCount());                productSalesDao.save(productSales);            }            products1.add(product1);            //openSearchService.openSearchProductPush(product1);        }        productDao.save(products1);    }    @Override    public List<Product> findGift() {        List<Product> giftProduct = productDao.findByStoreIdAndEnabledOrderBySalesPriceAsc("2", true);        return giftProduct;    }    public void dealProduct() {    }    @Override    public HomePageVo getStockHomeInfo(String storeId, List<String> typeIds, Pageable pageable, boolean status) {        Page<Product> products = null;        if (typeIds.size() == 0) {            products = productDao.findListByStoreIdAndEnabledAndStockEnabledAndHaveMatchProductEnabledIsFalseOrderByQuantityDesc(storeId,                    true, true, pageable);        } else {            products = productDao.findListByStoreIdAndEnabledAndStockEnabledAndProductType_IdIn(storeId,                    true, true, typeIds, pageable);        }        HomePageVo homePageVo = new HomePageVo(products.getTotalPages(), products.getTotalElements());        List<String> productIds = new ArrayList<>();        for (Product product : products) {            HomePageVo.ProductVo productVo = new HomePageVo.ProductVo(product.getId(),                    product.getName(), product.getProductType().getName(), product.getStockQuantityRatio(),                    product.getStockPrice(), product.getQuantity());            productIds.add(product.getId());            homePageVo.getProducts().add(productVo);        }        if (productIds.size() > 0 && status) {            /**             * 查询仓库库存数             */            StockProductVo signUpReqs = restTemplate.postForEntity(urlUtil.getProductUrl(),                    productIds, StockProductVo.class).getBody();            Map<String, StockProductVo.ProductVo> map = signUpReqs.getProducts().stream().                    collect(Collectors.toMap(StockProductVo.ProductVo::getId, productVo -> productVo));            for (HomePageVo.ProductVo productVo : homePageVo.getProducts()) {                StockProductVo.ProductVo signUpReq = map.get(productVo.getId());                if (signUpReq != null) {                    productVo.setWarehouseQuantity(signUpReq.getWarehouseQuantity());                }            }        }        return homePageVo;    }    @Override    public HomePageVo.ProductVo getProductInfo(Product product) {        HomePageVo.ProductVo productVo = new HomePageVo.ProductVo(product.getId(),                product.getName(), product.getProductType().getName(), product.getStockQuantityRatio(),                product.getStockPrice(), product.getQuantity());        StockProductVo signUpReqs = restTemplate.postForEntity(urlUtil.getProductUrl(),                Arrays.asList(product.getId()), StockProductVo.class).getBody();        if (signUpReqs.getProducts().size() > 0) {            productVo.setWarehouseQuantity(signUpReqs.getProducts().get(0).getWarehouseQuantity());        }        return productVo;    }    /**     * 商品入库     *     * @param barReq     * @return     */    @Override    public Result stockIn(StockBarReq barReq) throws Exception {        Store store = storeDao.findOne(barReq.getStoreId());        if (store == null) {            return new Result(400, "无该店铺信息");        }        Employee employee = employeeDao.findOne(barReq.getEmpId());        if (employee == null) {            return new Result(400, "无该操作人的信息");        }        List<InventoryFlowRequest> requests = new ArrayList<>();        for (StockBarReq.BarProduct product : barReq.getBarProducts()) {            if (barReq.getMold().equals(ProductMold.PRODUCT)) {                Product p = productDao.findOne(product.getProductId());                InventoryFlowRequest stockOut = new InventoryFlowRequest();                stockOut.setSkuId(p.getId() + "");                stockOut.setSkuName(p.getName());                stockOut.setSkuType(1);                stockOut.setStockLevel(StockLevel.BAR);                stockOut.setStoreId(barReq.getStoreId());                stockOut.setType(StockType.STOCK_IN);                stockOut.setSource(StockChangeReason.INNER_IN);                stockOut.setOperatorId(barReq.getEmpId());                stockOut.setOperatorName(barReq.getOperatorName());                stockOut.setNotes(barReq.getNotes());                stockOut.setMold(barReq.getMold());                stockOut.setQty(product.getQuantity());                requests.add(stockOut);            } else {                ProductMaterial productMaterial = productMaterialDao.findOne(Integer.valueOf(product.getProductId()));                InventoryFlowRequest stockOut = new InventoryFlowRequest();                stockOut.setSkuId(productMaterial.getId() + "");                stockOut.setSkuName(productMaterial.getName());                stockOut.setSkuType(2);                stockOut.setStockLevel(StockLevel.BAR);                stockOut.setStoreId(barReq.getStoreId());                stockOut.setType(StockType.STOCK_IN);                stockOut.setSource(StockChangeReason.INNER_IN);                stockOut.setOperatorId(barReq.getEmpId());                stockOut.setOperatorName(barReq.getOperatorName());                stockOut.setNotes(barReq.getNotes());                stockOut.setMold(barReq.getMold());                stockOut.setQty(product.getQuantity());                requests.add(stockOut);            }        }        stockTransactionService.flows(requests);        return new Result(200, "入库成功");    }    @Override    public Result checkBarInOrOut(BarCheckReq req) throws Exception {        StockCheck stockCheck = new StockCheck(req, StockLevel.BAR);        stockCheck.setMold(req.getMold());        List<StockCheckTransaction> list = new ArrayList<>();        //盘点更改库存        if (null == storeDao.findOne(req.getStoreId())) {            return new Result(400, "无店铺信息");        }        if (null == employeeDao.findOne(req.getOperatorId())) {            return new Result(400, "无改店员信息");        }        List<InventoryFlowRequest> requests = new ArrayList<>();        for (BarCheckReq.CheckBar in : req.getCheckBar()) {            String s = in.checkSockBarType();            if (s.equals("NO")) {                /**                 * 数量相等，只执行生成盘点记录                 */                //生成盘点记录                StockCheckTransaction s1 = new StockCheckTransaction(in, req.getStoreId(), req.getOperatorId(), req.getOperatorName());                s1.setMold(req.getMold());                list.add(s1);            } else if (s.equals("CHECK-OUT")) {                /**                 * 数量不等，执行更改库存操作，并且生成出库记录                 */                if (req.getMold().equals(ProductMold.PRODUCT)) {                    Product p = productDao.findOne(in.getProductId());                    log.info("商品{}库存变动 原{} 出库重置{}  method:{}", p.getId(), p.getQuantity(), in.getCheckNum(), "ProductServiceImpl.checkBarInOrOut");                    log.info("商品{}库存变动 传入参数{}", p.getId(), in);                    //生成盘点记录                    StockCheckTransaction s1 = new StockCheckTransaction(in, req.getStoreId(), req.getOperatorId(), req.getOperatorName());                    s1.setMold(req.getMold());                    list.add(s1);                    //吧台出库参数构建                    InventoryFlowRequest stockOut = new InventoryFlowRequest();                    stockOut.setSkuId(p.getId() + "");                    stockOut.setSkuName(in.getProductName());                    stockOut.setSkuType(1);                    stockOut.setStockLevel(StockLevel.BAR);                    stockOut.setStoreId(req.getStoreId());                    stockOut.setType(StockType.STOCK_OUT);                    stockOut.setSource(StockChangeReason.CHECK_OUT);                    stockOut.setOperatorId(req.getOperatorId());                    stockOut.setOperatorName(req.getOperatorName());                    stockOut.setNotes(req.getNotes());                    stockOut.setMold(req.getMold());                    stockOut.setQty(in.getCheckNum());                    requests.add(stockOut);                } else {                    ProductMaterial p = productMaterialDao.findOne(Integer.valueOf(in.getProductId()));                    log.info("商品{}库存变动 原{} 出库重置{}  method:{}", p.getId(), p.getStockQty(), in.getCheckNum(), "ProductServiceImpl.checkBarInOrOut");                    log.info("商品{}库存变动 传入参数{}", p.getId(), in);                    //生成盘点记录                    StockCheckTransaction s1 = new StockCheckTransaction(in, req.getStoreId(), req.getOperatorId(), req.getOperatorName());                    s1.setMold(req.getMold());                    list.add(s1);                    //生成changeTransaction                    InventoryFlowRequest stockOut = new InventoryFlowRequest();                    stockOut.setSkuId(p.getId() + "");                    stockOut.setSkuName(in.getProductName());                    stockOut.setSkuType(2);                    stockOut.setStockLevel(StockLevel.BAR);                    stockOut.setStoreId(req.getStoreId());                    stockOut.setType(StockType.STOCK_OUT);                    stockOut.setSource(StockChangeReason.CHECK_OUT);                    stockOut.setOperatorId(req.getOperatorId());                    stockOut.setOperatorName(req.getOperatorName());                    stockOut.setNotes(req.getNotes());                    stockOut.setMold(req.getMold());                    stockOut.setQty(in.getCheckNum());                    requests.add(stockOut);                }            } else if (s.equals("CHECK-IN")) {                /**                 * 数量不等，执行更改库存操作，并且生成入库记录                 */                if (req.getMold().equals(ProductMold.PRODUCT)) {                    Product p = productDao.findOne(in.getProductId());                    log.info("商品{}库存变动 原{} 入库重置{}  method:{}", p.getId(), p.getQuantity(), in.getCheckNum(), "ProductServiceImpl.checkBarInOrOut");                    log.info("商品{}库存变动 传入参数{}", p.getId(), in);                    //生成盘点记录                    StockCheckTransaction s1 = new StockCheckTransaction(in, req.getStoreId(), req.getOperatorId(), req.getOperatorName());                    s1.setMold(req.getMold());                    list.add(s1);                    //生成changeTransaction                    //吧台出库参数构建                    InventoryFlowRequest stockOut = new InventoryFlowRequest();                    stockOut.setSkuId(p.getId() + "");                    stockOut.setSkuName(in.getProductName());                    stockOut.setSkuType(1);                    stockOut.setStockLevel(StockLevel.BAR);                    stockOut.setStoreId(req.getStoreId());                    stockOut.setType(StockType.STOCK_IN);                    stockOut.setSource(StockChangeReason.CHECK_IN);                    stockOut.setOperatorId(req.getOperatorId());                    stockOut.setOperatorName(req.getOperatorName());                    stockOut.setNotes(req.getNotes());                    stockOut.setMold(req.getMold());                    stockOut.setQty(in.getCheckNum());                    requests.add(stockOut);                } else {                    ProductMaterial p = productMaterialDao.findOne(Integer.valueOf(in.getProductId()));                    log.info("商品{}库存变动 原{} 入库重置{}  method:{}", p.getId(), p.getStockQty(), in.getCheckNum(), "ProductServiceImpl.checkBarInOrOut");                    log.info("商品{}库存变动 传入参数{}", p.getId(), in);                    //生成盘点记录                    StockCheckTransaction s1 = new StockCheckTransaction(in, req.getStoreId(), req.getOperatorId(), req.getOperatorName());                    s1.setMold(req.getMold());                    list.add(s1);                    //生成changeTransaction                    InventoryFlowRequest stockOut = new InventoryFlowRequest();                    stockOut.setSkuId(p.getId() + "");                    stockOut.setSkuName(in.getProductName());                    stockOut.setSkuType(2);                    stockOut.setStockLevel(StockLevel.BAR);                    stockOut.setStoreId(req.getStoreId());                    stockOut.setType(StockType.STOCK_IN);                    stockOut.setSource(StockChangeReason.CHECK_IN);                    stockOut.setOperatorId(req.getOperatorId());                    stockOut.setOperatorName(req.getOperatorName());                    stockOut.setNotes(req.getNotes());                    stockOut.setMold(req.getMold());                    stockOut.setQty(in.getCheckNum());                    requests.add(stockOut);                }            }        }        stockTransactionService.flows(requests);        stockCheck.setItems(list);        checkOrderDao.save(stockCheck);        return new Result(200, "盘点成功");    }    @Override    public Result stockOut(StockBarReq barReq) throws Exception {        Store store = storeDao.findOne(barReq.getStoreId());        if (store == null) {            return new Result(400, "无该店铺信息");        }        Employee employee = employeeDao.findOne(barReq.getEmpId());        if (employee == null) {            return new Result(400, "无该操作人的信息");        }        for (StockBarReq.BarProduct product : barReq.getBarProducts()) {            if (barReq.getMold().equals(ProductMold.PRODUCT)) {                Product p = productDao.findOne(product.getProductId());                if (p.getQuantity() - product.getQuantity() < 0) {                    return new Result(400, "该商品库存数量不足，下架失败");                }            } else {                ProductMaterial material = productMaterialDao.findOne(Integer.valueOf(product.getProductId()));                if (material.getStockQty() - product.getQuantity() < 0) {                    return new Result(400, "该原料库存数量不足，下架失败");                }            }        }        List<InventoryFlowRequest> requests = new ArrayList<>();        for (StockBarReq.BarProduct product : barReq.getBarProducts()) {            if (barReq.getMold().equals(ProductMold.PRODUCT)) {                Product p = productDao.findOne(product.getProductId());                InventoryFlowRequest stockOut = new InventoryFlowRequest();                stockOut.setSkuId(p.getId() + "");                stockOut.setSkuName(p.getName());                stockOut.setSkuType(1);                stockOut.setStockLevel(StockLevel.BAR);                stockOut.setStoreId(barReq.getStoreId());                stockOut.setType(StockType.STOCK_OUT);                stockOut.setSource(StockChangeReason.INNER_OUT);                stockOut.setOperatorId(barReq.getEmpId());                stockOut.setOperatorName(barReq.getOperatorName());                stockOut.setNotes(barReq.getNotes());                stockOut.setMold(barReq.getMold());                stockOut.setQty(-product.getQuantity());                requests.add(stockOut);            } else {                ProductMaterial productMaterial = productMaterialDao.findOne(Integer.valueOf(product.getProductId()));                InventoryFlowRequest stockOut = new InventoryFlowRequest();                stockOut.setSkuId(productMaterial.getId() + "");                stockOut.setSkuName(productMaterial.getName());                stockOut.setSkuType(2);                stockOut.setStockLevel(StockLevel.BAR);                stockOut.setStoreId(barReq.getStoreId());                stockOut.setType(StockType.STOCK_OUT);                stockOut.setSource(StockChangeReason.INNER_OUT);                stockOut.setOperatorId(barReq.getEmpId());                stockOut.setOperatorName(barReq.getOperatorName());                stockOut.setNotes(barReq.getNotes());                stockOut.setMold(barReq.getMold());                stockOut.setQty(-product.getQuantity());                requests.add(stockOut);            }        }        stockTransactionService.flows(requests);        return new Result(200, "入库成功");    }    @Override    public Page<StockChangeTransaction> findListBySkuIdAndTypeAndStockLevel(BarAssembleReq req, Pageable pageable) {        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));        Specification<StockChangeTransaction> spec = (root, criteriaQuery, criteriaBuilder) -> {            List<Predicate> predicates = new ArrayList<>();            if (!req.getReason().equals(StockChangeReason.ALL)) {                predicates.add(criteriaBuilder.equal(root.get("source"), req.getReason()));            }            if (!req.getType().equals(StockType.ALL)) {                predicates.add(criteriaBuilder.equal(root.get("type"), req.getType()));            }            if (!StringUtils.isBlank(req.getProductId())) {                predicates.add(criteriaBuilder.equal(root.get("skuId"), req.getProductId()));            }            if (!StringUtils.isBlank(req.getBegin()) && !StringUtils.isBlank(req.getEnd())) {                try {                    predicates.add(criteriaBuilder.between(root.get("addTime"), sdf.parse(req.getBegin()), sdf.parse(req.getEnd())));                } catch (ParseException e) {                    e.printStackTrace();                }            }            predicates.add(criteriaBuilder.equal(root.get("mold"), req.getMold()));            predicates.add(criteriaBuilder.equal(root.get("stockLevel"), StockLevel.BAR));            predicates.add(criteriaBuilder.equal(root.get("storeId"), req.getStoreId()));            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));        };        Page<StockChangeTransaction> p = stockTransactionDao.findAll(spec, new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), new Sort(Sort.Direction.DESC, "addTime")));        return p;    }    @Override    public Map<String, Object> findHomePageProduct(String storeId, Pageable pageable) {        Map<String, Object> map = new HashMap<>();        List<ProductInVo> list = new ArrayList<>();        Page<Product> lists = productDao.findListByStoreIdAndEnabledAndStockEnabledAndHaveMatchProductEnabledIsFalseOrderByQuantityDesc(storeId, true, true, pageable);        for (Product p : lists) {            ProductInVo inVo = new ProductInVo(p.getName(), p.getQuantity(), p.getProductType().getName());            inVo.setAmount(p.getSalesPrice());            list.add(inVo);        }        map.put("products", list);        map.put("totalElements", lists.getTotalElements());        map.put("totalPages", lists.getTotalPages());        return map;    }    @Override    public Map<String, Object> findHomePageMaterial(String storeId, Pageable pageable) {        Map<String, Object> map = new HashMap<>();        List<ProductInVo> list = new ArrayList<>();        Page<ProductMaterial> lists = productMaterialDao.findListByStoreId(storeId, pageable);        for (ProductMaterial p : lists) {            ProductInVo inVo = new ProductInVo();            inVo.setName(p.getName());            inVo.setQuantity(p.getStockQty());            list.add(inVo);        }        map.put("products", list);        map.put("totalElements", lists.getTotalElements());        map.put("totalPages", lists.getTotalPages());        return map;    }    /**     * admin 饼状图+退单显示     *     * @param storeId     * @param time     * @return     */    @Override    public Map<String, Object> findStoreBill(String begin, String end, String type, String orderId, String storeId, String time, String source, String workShiftId, String empMobile, Pageable pageable, String productName) {        Map<String, Object> map = new HashMap<>();        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));        AdminPayBill adminPayBill = new AdminPayBill();        AdminPayBill refundBill = new AdminPayBill();        List<Object[]> channel;        List<Object[]> refundChannel;        List<AdminOrderRes> orderRes = new ArrayList<>();        List<Object[]> billList;        List<Object[]> refundBillList;        Date endDate = new Date();        Date startDate = new Date();        List<Object[]> successAndRefundCount = null;        List<OrderStatus> orderStatuses = getOrderStatus();        try {            if (null == orderId) {                //根据时间查询payment                if (source.equals("boss") || source.equals("store")) {                    if (StringUtils.equals(type, "DAY")) {                        startDate = MyDateUtils.getEarliest(sdf.parse(time));                        endDate = MyDateUtils.getLastest(sdf.parse(time));                    } else {                        startDate = simpleDateFormat.parse(begin);                        endDate = simpleDateFormat.parse(end);                    }                }                if (source.equals("workShift")) {                    WorkShift workShift = workShiftDao.findOne(workShiftId);                    startDate = workShift.getBeginTime();                    endDate = workShift.getEndTime();                    storeId = workShift.getStoreId();                }                final String workShiftStoreId = storeId;                final Date getBegin = startDate;                final Date getEnd = endDate;                Specification<Order> spec = (root, criteriaQuery, criteriaBuilder) -> {                    List<Predicate> predicates = new ArrayList<>();                    predicates.add(criteriaBuilder.between(root.get("paymentTime"), getBegin, getEnd));                    predicates.add(criteriaBuilder.equal(root.get("storeId"), workShiftStoreId));                    final CriteriaBuilder.In<Object> sectionId = criteriaBuilder.in(root.get("status"));                    for (OrderStatus section : orderStatuses) {                        sectionId.value(section);                    }                    predicates.add(criteriaBuilder.not(sectionId));                    if (StringUtils.isNotBlank(productName)) {                        predicates.add(criteriaBuilder.like(root.join("items").get("productName"), "%" + productName + "%"));                    }                    predicates.add(criteriaBuilder.isTrue(root.get("enabled")));                    if (StringUtils.isNotBlank(empMobile)) {                        predicates.add(criteriaBuilder.equal(root.get("creatorId"), empMobile));                    }                    criteriaQuery.distinct(true);                    return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));                };                //封装返回实体                Page<Order> pageList = orderDao.findAll(spec, new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), new Sort(Sort.Direction.DESC, "paymentTime")));                log.info("workShiftId{},pageList{}", workShiftId, pageList);                //判断是页面来源                //BOSS的对账单                if (source.equals("boss")) {                    //支付方式+金额（已更改为通过订单）                    List<Object[]> list = orderDao.findListByStoreIdAndSuccessAndAddTimeBetween(startDate, endDate, storeId);                    //总金额（已更改为通过订单）                    BigDecimal bigDecimal = orderDao.findSumAmount(startDate, endDate, storeId);                    if (bigDecimal == null) {                        map.put("allAmount", 0.00);                    } else {                        map.put("allAmount", bigDecimal);                    }                    //处理金额数据                    adminPayBill = dealChannelAndAmountData(adminPayBill, list);                    String list2 = dealObject(adminPayBill, list);                    map.put("adminPayBill", list2);                }                //店铺的对账单                else if (source.equals("store")) {                    //这个是支付方式的统计                    if (null != empMobile && !"".equals(empMobile)) {                        // pageList = orderDao.findByStoreIdAndPaymentTimeBetweenAndStatusNotInAndEnabledAndCreatorIdOrderByPaymentTimeDesc(storeId, startDate, endDate, orderStatuses, true, empMobile, pageable);                        billList = orderDao.findEmpBill(startDate, endDate, storeId, empMobile);                        //统计退款的方式                        refundBillList = orderDao.findRefundEmpBill(startDate, endDate, storeId, empMobile);                        //付款方式和笔数（成功）                        channel = orderDao.findCountEmpPayChannelByDate(startDate, endDate, storeId, empMobile);                        refundChannel = orderDao.findCountEmpRefundPayChannelByDate(startDate, endDate, storeId, empMobile);                        successAndRefundCount = orderDao.findSuccessAndRefundEmpCount(startDate, endDate, storeId, empMobile);                    } else {                        //pageList = orderDao.findByStoreIdAndPaymentTimeBetweenAndStatusNotInAndEnabledOrderByPaymentTimeDesc(storeId, startDate, endDate, orderStatuses, true, pageable);                        billList = orderDao.findBill(startDate, endDate, storeId);                        //统计退款的方式                        refundBillList = orderDao.findRefundBill(startDate, endDate, storeId);                        //付款方式和笔数（成功）                        channel = orderDao.findCountPayChannelByDate(startDate, endDate, storeId);                        refundChannel = orderDao.findCountRefundPayChannelByDate(startDate, endDate, storeId);                        successAndRefundCount = orderDao.findSuccessAndRefundCount(startDate, endDate, storeId);                    }                    //处理金额数据                    adminPayBill = dealChannelAndAmountData(adminPayBill, billList);                    //处理笔数                    adminPayBill = dealChannelAndCountData(adminPayBill, channel);                    refundBill = dealChannelAndAmountData(refundBill, refundBillList);                    refundBill = dealChannelAndCountData(refundBill, refundChannel);                    String objects = dealObject(adminPayBill, channel);                    String refundObjects = dealObject(refundBill, refundChannel);                    map.put("adminPayBill", objects);                    map.put("adminRefundBill", refundObjects);                }                //员工的交班对账单                else if (source.equals("workShift")) {                    WorkShift workShift = workShiftDao.findOne(workShiftId);                    long cha = workShift.getEndTime().getTime() - workShift.getBeginTime().getTime();                    //数据校正                    if (cha > 50 * 3600000) {                        map.put("successTotalAmount", 0.0);                        map.put("refundTotalAmount", 0.0);                        map.put("successCount", 0.0);                        map.put("refundCount", 0.0);                        map.put("data", orderRes);                        map.put("totalElements", 0);                        map.put("totalPages", 0);                        map.put("adminPayBill", workShift.getPaymentStatics());                        return map;                    }                    successAndRefundCount = orderDao.findWorkShiftCountSuccessAndRefundCount(workShift.getBeginTime(), workShift.getEndTime(), workShift.getStoreId());                    //  pageList = orderDao.findByStoreIdAndPaymentTimeBetweenAndStatusNotInAndEnabledOrderByPaymentTimeDesc(workShift.getStoreId(), workShift.getBeginTime(), workShift.getEndTime(), orderStatuses, true, pageable);                    if (null == workShift.getPaymentStatics()) {                        PaymentVo paymentVo = paymentService.getNetCostTotal(workShift.getStoreId(), workShift.getBeginTime(), workShift.getEndTime());                        if (workShift.getThirdPartyAmount() > 0 && workShift.getThirdPartyAmount() - paymentVo.getCashAmount() >= 0) {                            workShift.setCashAmount(workShift.getCashAmount() + (workShift.getThirdPartyAmount() - paymentVo.getCashAmount()));                        }                        WorkShift workShift1 = workShiftDao.save(workShift);                        WorkShiftVo workShiftVo = new WorkShiftVo();                        workShiftVo.setCashAmount(workShift1.getCashAmount());                        workshiftService.updateWorkShift(workShift1, workShiftVo, paymentVo.getCashAmount(), "generate");                    }                    map.put("adminPayBill", workShift.getPaymentStatics());                }                //用于复用store和workShift                if (source.equals("workShift") || source.equals("store")) {                    for (Order p : pageList) {                        AdminOrderRes res = new AdminOrderRes(p);                        orderRes.add(res);                    }                    map.put("data", orderRes);                    map.put("totalElements", pageList.getTotalElements());                    map.put("totalPages", pageList.getTotalPages());                }                if (source.equals("workShift") || source.equals("store")) {                    //根据时间统计成功金额，退款金额，成功笔数，退款笔数                    for (Object[] object : successAndRefundCount) {                        if (null == object[2] && null == object[3]) {                            map.put("successTotalAmount", 0.0);                            map.put("refundTotalAmount", 0.0);                            map.put("successCount", 0.0);                            map.put("refundCount", 0.0);                        } else {                            map.put("successTotalAmount", object[0]);                            map.put("refundTotalAmount", Math.abs(Double.valueOf(object[1].toString())));                            map.put("successCount", object[2]);                            map.put("refundCount", object[3]);                        }                    }                }                //根据时间统计成功金额，退款金额，成功笔数，退款笔数                return map;            } else {                //根据订单ID统计支付宝，微信，现金 金额                billList = orderDao.findBillByOrderId(orderId);                channel = orderDao.findCountPayChannelByOrderId(orderId);                //付款的方式和金额                //处理金额数据                adminPayBill = dealChannelAndAmountData(adminPayBill, billList);                //处理笔数                dealChannelAndCountData(adminPayBill, channel);                //根据订单id统计成功金额，退款金额，成功笔数，退款笔数                successAndRefundCount = orderDao.findSuccessAndRefundCountByOrderId(orderId);                //根据订单id查询订单详情                Order order = orderDao.findOne(orderId);                orderRes = new ArrayList<>();                String objects = dealObject(adminPayBill, channel);                AdminOrderRes res = new AdminOrderRes(order);                orderRes.add(res);                map.put("adminPayBill", objects);                map.put("data", orderRes);                //根据订单id统计成功金额，退款金额，成功笔数，退款笔数                for (Object[] object : successAndRefundCount) {                    if (null == object[2] && null == object[3]) {                        map.put("successTotalAmount", 0.0);                        map.put("refundTotalAmount", 0.0);                        map.put("successCount", 0.0);                        map.put("refundCount", 0.0);                    } else {                        map.put("successTotalAmount", object[0]);                        map.put("refundTotalAmount", Math.abs(Double.valueOf(object[1].toString())));                        map.put("successCount", object[2]);                        map.put("refundCount", object[3]);                    }                }                return map;            }        } catch (ParseException e) {            e.printStackTrace();            log.info("时间转换异常:{}", e);        }        return map;    }    @Override    public String createProductData(String storeId) {        //在把模板店铺下的商品找出来        List<Product> productList = productDao.findListByStoreIdAndEnabledAndIdNotOrderBySalesPriceAsc("1", true, "0");        //把模板店铺下的商品分类找出来（系统网费）        List<ProductType> productType = productTypeDao.findByStoreId("1");        for (Product p : productList) {            for (ProductType type : productType) {                Product product = new Product();                BeanUtils.copyProperties(p, product);                product.setId(UuidUtil.getUuid());                product.setStoreId(storeId);                product.setProductType(type);                productDao.save(product);            }        }        return "保存完成";    }    @Override    public Map<Object, Object> getSalesCount(String storeId, String time, String year, String month, List<String> type, String source, String timer, String to, double fromSecond, double toSecond, boolean judge, String orderSource, String typeAll) {        Date from = null;        Date end = null;        if (source.equals("DAY")) {            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");            simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));            try {                Date dataSourceTime = simpleDateFormat.parse(time);                from = MyDateUtils.getEarliest(dataSourceTime);                end = MyDateUtils.getLastest(dataSourceTime);            } catch (ParseException e) {                log.info("时间转换异常");                e.printStackTrace();            }        } else if (source.equals("MONTH")) {            String date = year + "-" + month;            from = MyDateUtils.getMinMonthDate(date);            end = MyDateUtils.getMaxMonthDate(date);        } else {            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");            simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));            try {                from = simpleDateFormat.parse(timer);                end = simpleDateFormat.parse(to);            } catch (ParseException e) {                log.info("时间转换异常");                e.printStackTrace();            }        }        if (typeAll.equals("ALL")) {            type.clear();            type = productDao.selectProductTypeGroupByProductId(storeId);        }        BeanPropertyRowMapper itemMapper = new BeanPropertyRowMapper<>(SalesItem.class);        itemMapper.setPrimitivesDefaultedForNullValue(true);        BeanPropertyRowMapper<SalesCount> sales = new BeanPropertyRowMapper<>(SalesCount.class);        sales.setPrimitivesDefaultedForNullValue(true);        Map<Object, Object> map = new HashMap<>();        List<SalesItem> items = new ArrayList<>();        SalesCount salesCount = new SalesCount();        List<Object[]> objects = new ArrayList<>();        List<Object[]> salesCountData = new ArrayList<>();        List<Object[]> channel = new ArrayList<>();        if (storeId.equals("1")) {            DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");            DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyyMM");            LocalDateTime dateTime = LocalDateTime.parse(timer, inputFormatter);            String resultMonth = dateTime.format(outputFormatter);            String s = "";            for (int i = 0; i < type.size(); i++) {                if (i == type.size() - 1) {                    s += "'" + type.get(i) + "'";                } else {                    s += "'" + type.get(i) + "',";                }            }            String firstSql = String.format("SELECT product.`parent_type_name` AS parentTypeName   ,product.`name` AS name   ,product.`sales_price` AS salesPrice  , ifnull(SUM(sales.amount), 0) as amount     , ifnull(sum(sales.qty),0) AS qty     , product.`type_name` AS typeName  FROM(SELECT * FROM `product` WHERE `store_id`= ?) as product  LEFT JOIN(SELECT sum(`quantity`) as qty, SUM(`deal_price`) as amount, `product_id` FROM `%s` oi WHERE `order_id` IN(SELECT id  FROM `%s`  WHERE `store_id`= ?  and `status`  in('FINISHED','UNFINISHED') AND `payment_time`> ? AND `payment_time`< ? AND `enabled`= 1) GROUP BY `product_id`) sales on product.id= sales.product_id  WHERE  product.`parent_type_name` in (" + s + ") AND qty>0 GROUP BY product.`name` order BY qty DESC  ", "order_item_" + resultMonth, "order_" + resultMonth);            String twoSql = String.format("SELECT  ifnull(SUM(sales.amount), 0) as amount,ifnull(sum(sales.qty), 0) AS qty FROM(SELECT * FROM `product`WHERE `store_id`= ?) as product LEFT JOIN(SELECT sum(`quantity`) as qty, SUM(`deal_price`) as amount, `product_id` FROM `%s`  oi WHERE `order_id` IN(SELECT id FROM `%s`WHERE `store_id`= ? and `status`  in('FINISHED','UNFINISHED') AND `payment_time` > ? AND`payment_time` < ?  AND `enabled`= 1)GROUP BY `product_id`) sales on product.id= sales.product_id WHERE   product.`parent_type_name`IN  (" + s + ") order BY qty DESC   ", "order_item_" + resultMonth, "order_" + resultMonth);            String threeSql = String.format("SELECT pr.channel as channel, SUM(pr.amount) as amount FROM `product` p, (SELECT r.product_id, r.channel,sum(r.`quantity`) as qty, SUM(r.`deal_price`) as amount FROM ( SELECT oi.*,o.channel FROM `%s` oi, (SELECT id, `channel` FROM `%s`  WHERE `store_id`= ?  and `status` in('FINISHED', 'UNFINISHED')  AND `payment_time`>?  AND `payment_time`< ? AND `enabled`= 1) o WHERE oi.`order_id` = o.id ) as r GROUP BY r.product_id, r.channel) as pr WHERE p.`store_id`= ? and p.id = pr.product_id and p.`parent_type_name` in (" + s + ") GROUP BY pr.channel", "order_item_" + resultMonth, "order_" + resultMonth);            log.info("第一条sql语句{}", firstSql);            log.info("第二条sql语句{}", twoSql);            log.info("第三条sql语句{}", threeSql);            BeanPropertyRowMapper firstItem = new BeanPropertyRowMapper<>(SalesItem.class);            firstItem.setPrimitivesDefaultedForNullValue(true);            List<SalesItem> salesItems = jdbc.query(firstSql, firstItem, storeId, storeId, from, end);            log.info("查询出来的结果{}", JSON.toJSON(salesItems));            BeanPropertyRowMapper twoItem = new BeanPropertyRowMapper<>(SalesCount.class);            twoItem.setPrimitivesDefaultedForNullValue(true);            List<SalesCount> data = jdbc.query(twoSql, twoItem, storeId, storeId, from, end);            log.info("查询出来的结果{}", JSON.toJSON(data));            BeanPropertyRowMapper threeItem = new BeanPropertyRowMapper<>(ChannelAmount.class);            threeItem.setPrimitivesDefaultedForNullValue(true);            List<ChannelAmount> channelAmounts = jdbc.query(threeSql, threeItem, storeId, from, end, storeId);            log.info("查询出来的结果{}", JSON.toJSON(channelAmounts));            items = salesItems;            salesCount = data.get(0);            ChannelResult result = new ChannelResult();            for (ChannelAmount channelAmount : channelAmounts) {                if (channelAmount.getChannel().startsWith("pay.alipay")) {                    result.setAliAmount(channelAmount.getAmount());                }                if (channelAmount.getChannel().startsWith("pay.wechat")) {                    result.setWechatAmount(channelAmount.getAmount());                }                if (channelAmount.getChannel().startsWith("pay.unionpay")) {                    result.setUnionpayAmount(channelAmount.getAmount());                }                if (channelAmount.getChannel().startsWith("MEMBER")) {                    result.setMemberAmount(channelAmount.getAmount());                }                if (channelAmount.getChannel().startsWith("CASH")) {                    result.setCashAmount(channelAmount.getAmount());                }            }            map.put("result", channel);            map.put("channel", result);            map.put("data", items);            map.put("allQty", salesCount.getQty());            map.put("allAmount", salesCount.getAmount());            return map;        } else {            if (judge) {                if ("ALL".equals(orderSource)) {                    objects = productDao.countByProductTypeNameAndSecond(storeId, storeId, from, end, fromSecond, toSecond, type);                    salesCountData = productDao.countSalesCountAndSecond(storeId, storeId, from, end, fromSecond, toSecond, type);                    channel = productDao.groupByChannel(storeId, from, end, storeId, type);                } else {                    objects = productDao.countByProductTypeNameAndSecondAndOrderSource(storeId, storeId, from, end, fromSecond, toSecond, orderSource, type);                    salesCountData = productDao.countSalesCountAndSecondAndOrderSource(storeId, storeId, from, end, fromSecond, toSecond, orderSource, type);                    channel = productDao.groupByChannelOrderSource(storeId, from, end, source, storeId, type);                }            } else {                if ("ALL".equals(orderSource)) {                    objects = productDao.countByProductTypeName(storeId, from, end, type);                    salesCountData = productDao.countSalesCount(storeId, storeId, from, end, type);                    channel = productDao.groupByChannel(storeId, from, end, storeId, type);                } else {                    objects = productDao.countByProductTypeNameAndOrderSource(storeId, from, end, orderSource, type);                    salesCountData = productDao.countSalesCountAndOrderSource(storeId, storeId, from, end, orderSource, type);                    channel = productDao.groupByChannelOrderSource(storeId, from, end, source, storeId, type);                }            }            for (Object[] ob : objects) {                SalesItem salesItem = new SalesItem(ob);                items.add(salesItem);            }            ChannelResult result = new ChannelResult();            for (Object[] data : salesCountData) {                salesCount.setAmount(Double.valueOf(data[0].toString()));                salesCount.setQty(Integer.valueOf(data[1].toString()));            }            for (Object[] objects1 : channel) {                if (objects1[0].toString().startsWith("pay.alipay")) {                    result.setAliAmount(Double.valueOf(objects1[1].toString()));                }                if (objects1[0].toString().startsWith("pay.wechat")) {                    result.setWechatAmount(Double.valueOf(objects1[1].toString()));                }                if (objects1[0].toString().startsWith("pay.unionpay")) {                    result.setUnionpayAmount(Double.valueOf(objects1[1].toString()));                }                if (objects1[0].toString().startsWith("MEMBER")) {                    result.setMemberAmount(Double.valueOf(objects1[1].toString()));                }                if (objects1[0].toString().startsWith("CASH")) {                    result.setCashAmount(Double.valueOf(objects1[1].toString()));                }            }            map.put("result", channel);            map.put("channel", result);            map.put("data", items);            map.put("allQty", salesCount.getQty());            map.put("allAmount", salesCount.getAmount());            return map;        }    }    @Override    public List<Product> findAllGift() {        return productDao.findByStoreIdAndEnabled("2", true);    }    @Override    @Transactional    public Map<String, Object> updateGift(GiftReq req) {        Product product = productDao.findOne(req.getId());        Map<String, Object> map = new HashMap<>();        product.setName(req.getName());        product.setSalesPrice(req.getSalesPrice());        product.setImageURL(req.getProductUrl());        Product returnProduct = productDao.save(product);        map.put("result", new Result(200, "修改成功"));        map.put("data", returnProduct);        return map;    }    @Override    @Transactional    public void updateProductTimeSlot(UpdateProductTimeSlot slot) {        Product product = productDao.findOne(slot.getProductId());        product.setMemberShow(slot.isMemberShow());        product.setMemberPrice(slot.getMemberPrice());        product.setDisPrice(slot.getDisPrice());        product.setDisShow(slot.isDisShow());        product.setNowHours(slot.getBeginTime());        product.setTomorrowHour(slot.getEndTime());        product.setCross(true);        product.setDisCom(slot.getDisCom());        productDao.save(product);    }    @Override    public Result updateShowOrPurchase(ShowEnabledAndPurchaseReq req) {        Product product = productDao.findOne(req.getProductId());        product.setShowEnabled(req.isShowEnabled());        product.setPurchaseEnabled(req.isPurchaseEnabled());        return new Result(200, "修改成功");    }    @Override    public Map<Object, Object> getSalesItem(String storeId, String startTime, String endTime) {        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        Map<Object, Object> map = new HashMap<>();        try {            Date start = sdf.parse(startTime);            Date end = sdf.parse(endTime);            //开始            Date startLastest = MyDateUtils.getLastest(start);            Date startEarliest = MyDateUtils.getEarliest(start);            //结束            Date endLastest = MyDateUtils.getLastest(end);            Date endEarliest = MyDateUtils.getEarliest(end);            BeanPropertyRowMapper itemMapper = new BeanPropertyRowMapper<>(SalesItem.class);            itemMapper.setPrimitivesDefaultedForNullValue(true);            List<SalesItem> items;            List<SalesItem> salesItems;            items = jdbc.query("SELECT product.`parent_type_name` AS typeName,product.`name` AS name,product.`sales_price` AS salesPrice, ifnull(SUM(sales.amount), 0) as amount, ifnull(sum(sales.qty),0) AS qty FROM(SELECT * FROM `product` WHERE `store_id`= ?) as product  LEFT JOIN(SELECT sum(`quantity`) as qty, SUM(`deal_price`) as amount, `product_id` FROM `order_item` WHERE `order_id` IN(SELECT id  FROM `order`  WHERE `store_id`= ?  and `status`  in('FINISHED','UNFINISHED')  AND `payment_time`>= ? AND `payment_time`<= ? AND `status` IN('UNFINISHED', 'FINISHED') AND `enabled`= 1) GROUP BY `product_id`) sales on product.id= sales.product_id  WHERE qty >0  GROUP BY typeName order BY qty DESC "                    , itemMapper, storeId, storeId, startEarliest, startLastest);            salesItems = jdbc.query("SELECT product.`parent_type_name` AS typeName,product.`name` AS name,product.`sales_price` AS salesPrice, ifnull(SUM(sales.amount), 0) as amount, ifnull(sum(sales.qty),0) AS qty FROM(SELECT * FROM `product` WHERE `store_id`= ?) as product  LEFT JOIN(SELECT sum(`quantity`) as qty, SUM(`deal_price`) as amount, `product_id` FROM `order_item` WHERE `order_id` IN(SELECT id  FROM `order`  WHERE `store_id`= ?  and `status`  in('FINISHED','UNFINISHED')  AND `payment_time`>= ? AND `payment_time`<= ? AND `status` IN('UNFINISHED', 'FINISHED') AND `enabled`= 1) GROUP BY `product_id`) sales on product.id= sales.product_id  WHERE qty >0  GROUP BY typeName order BY qty DESC "                    , itemMapper, storeId, storeId, endEarliest, endLastest);            map.put("startSalesItem", items);            map.put("endSalesItem", salesItems);        } catch (ParseException e) {            e.printStackTrace();            log.info("时间转换异常");        }        return map;    }    @Override    public Page<Product> getTemplate(Pageable pageable) {        Page<Product> page = productDao.findByStoreId("9f5afd60-e952-11e7-a26a-83436326b6c5", pageable);        return page;    }    @Override    public Page<Product> productSearch(String name, Pageable pageable) {        name.trim();        Page<Product> page;        if (ValidatorUtil.isChinese(name)) {            String s = "%" + name + "%";            page = productDao.findAllByStoreIdAndNameLike("9f5afd60-e952-11e7-a26a-83436326b6c5", s, pageable);        } else {            name = name.toLowerCase();            page = productDao.findAllByStoreIdAndPinyinLike("9f5afd60-e952-11e7-a26a-83436326b6c5", name, pageable);        }        return page;    }    @Override    public Result deleteProduct(String productId) {        productDao.delete(productId);        return new Result(200, "删除成功", null);    }    @Override    public Result updateProduct(SalesProductReq req) {        Product product = productDao.findOne(req.getId());        if (!product.getName().equals(req.getName())) {            List<Product> judgeProduct = productDao.findByStoreIdAndName("9f5afd60-e952-11e7-a26a-83436326b6c5", req.getName());            if (!judgeProduct.isEmpty()) {                return new Result(400, "该名字已存在，请重新填写商品名字后再进行修改。", null);            }        } else {            product.setName(req.getName());            product.setSalesPrice(req.getAmount());            product.setImageURL(req.getImageUrl());            productDao.save(product);        }        return new Result(200, "修改成功", null);    }    @Override    public Result getOnline(String time, String storeId) {        Date lastMonthBegin = MyDateUtils.getMinMonthDate(time);        Date lastMonthEnd = MyDateUtils.getMaxMonthDate(time);        //加减月份并获取该月的第一天的开始时间        Date nowMonthBegin = MyDateUtils.getMinMonthDate(MyDateUtils.increaseStringMonth(time, 1));        Date nowMonthEnd = MyDateUtils.getMaxMonthDate(MyDateUtils.increaseStringMonth(time, 1));        //上月的        WorkShift lastWorkShift = workShiftDao.findTop1ByStoreIdAndClosedAndAddTimeBetween(storeId, true, lastMonthBegin, lastMonthEnd);        WorkShift nowWorkShift = workShiftDao.findTop1ByStoreIdAndClosedAndAddTimeBetween(storeId, true, nowMonthBegin, nowMonthEnd);        if (lastWorkShift == null || nowWorkShift == null) {            Map map = new HashMap();            map.put("amount", 0);            map.put("begin", "");            map.put("end", "");            return new Result(400, "没有获取到交班数据", map);        }        List<BigDecimal> onlinePay = orderDao.getOnlinePay(lastWorkShift.getBeginTime(), nowWorkShift.getBeginTime(), storeId);        double amount = 0;        for (BigDecimal objects : onlinePay) {            BigDecimal big2 = new BigDecimal(Double.valueOf(10000));            amount += objects.multiply(big2).doubleValue();        }        Map map = new HashMap();        map.put("amount", amount / 10000);        map.put("begin", lastWorkShift.getBeginTime());        map.put("end", nowWorkShift.getBeginTime());        return new Result(200, "数据获取成功", map);    }    public AdminPayBill dealChannelAndAmountData(AdminPayBill adminPayBill, List<Object[]> billList) {        for (Object[] obj : billList) {            if (obj[0].toString().startsWith("pay.alipay") || obj[0].equals("ALIPAY") || obj[0].equals("alipay")) {                adminPayBill.setAlipayAmount(adminPayBill.sum(adminPayBill.getAlipayAmount(), Double.valueOf(obj[1].toString())));            } else if (obj[0].equals("WECHATPAY") || obj[0].toString().startsWith("pay.wechat") || obj[0].toString().startsWith("pay.weixin") || obj[0].toString().startsWith("wxpay")) {                adminPayBill.setWechatAmount(adminPayBill.sum(adminPayBill.getWechatAmount(), Double.valueOf(obj[1].toString())));            } else if (obj[0].toString().startsWith("pay.bestpay")) {                adminPayBill.setWingPayAmount(adminPayBill.sum(adminPayBill.getWingPayAmount(), Double.valueOf(obj[1].toString())));            } else if (obj[0].toString().startsWith("pay.jdpay")) {                adminPayBill.setJdMicroPayAmount(adminPayBill.sum(adminPayBill.getJdMicroPayAmount(), Double.valueOf(obj[1].toString())));            } else if (obj[0].toString().startsWith("pay.qq") || obj[0].toString().startsWith("qqpay")) {                adminPayBill.setQqMicroPayAmount(adminPayBill.sum(adminPayBill.getQqMicroPayAmount(), Double.valueOf(obj[1].toString())));            } else if (obj[0].toString().startsWith("pay.shiming")) {                adminPayBill.setSmMicroPayAmount(adminPayBill.sum(adminPayBill.getSmMicroPayAmount(), Double.valueOf(obj[1].toString())));            } else if (obj[0].toString().startsWith("pay.unionpay") || obj[0].equals("UNIONPAY") || obj[0].equals("unionpay")) {                adminPayBill.setUnionPayAmount(adminPayBill.sum(adminPayBill.getUnionPayAmount(), Double.valueOf(obj[1].toString())));            } else if (obj[0].equals("CASH") || obj[0].equals("ALIPAY_CASH") || obj[0].equals("WECHATPAY_CASH")) {                adminPayBill.setCashAmount(adminPayBill.sum(adminPayBill.getCashAmount(), Double.valueOf(obj[1].toString())));            } else if (obj[0].equals("MEMBER")) {                adminPayBill.setMemberAmount(adminPayBill.sum(adminPayBill.getMemberAmount(), Double.valueOf(obj[1].toString())));            }        }        return adminPayBill;    }    public AdminPayBill dealChannelAndCountData(AdminPayBill adminPayBill, List<Object[]> billList) {        for (Object[] obj : billList) {            if (obj[0].toString().startsWith("pay.alipay") || obj[0].equals("ALIPAY")) {                adminPayBill.setAliCount(adminPayBill.getAliCount() + Integer.valueOf(obj[1].toString()));            } else if (obj[0].equals("WECHATPAY") || obj[0].toString().startsWith("pay.weixin") || obj[0].toString().startsWith("pay.wechat")) {                adminPayBill.setWxCount(adminPayBill.getWxCount() + Integer.valueOf(obj[1].toString()));            } else if (obj[0].toString().startsWith("pay.bestpay")) {                adminPayBill.setWingCount(adminPayBill.getWingCount() + Integer.valueOf(obj[1].toString()));            } else if (obj[0].toString().startsWith("pay.jdpay")) {                adminPayBill.setJdCount(adminPayBill.getJdCount() + Integer.valueOf(obj[1].toString()));            } else if (obj[0].toString().startsWith("pay.qq")) {                adminPayBill.setQqCount(adminPayBill.getQqCount() + Integer.valueOf(obj[1].toString()));            } else if (obj[0].toString().startsWith("pay.shiming")) {                adminPayBill.setSmCount(adminPayBill.getSmCount() + Integer.valueOf(obj[1].toString()));            } else if (obj[0].toString().startsWith("pay.unionpay") || obj[0].equals("UNIONPAY")) {                adminPayBill.setUnionCount(adminPayBill.getUnionCount() + Integer.valueOf(obj[1].toString()));            } else if (obj[0].equals("CASH") || obj[0].equals("ALIPAY_CASH") || obj[0].equals("WECHATPAY_CASH")) {                adminPayBill.setCashCount(adminPayBill.getCashCount() + Integer.valueOf(obj[1].toString()));            } else if (obj[0].equals("MEMBER")) {                adminPayBill.setMemberCount(adminPayBill.getMemberCount() + Integer.valueOf(obj[1].toString()));            }        }        return adminPayBill;    }    public String dealObject(AdminPayBill adminPayBill, List<Object[]> objects) {        JSONObject jsonObject = new JSONObject();        List<Map<Object, Object>> jsonData = new ArrayList<>();        Map<Object, Object> map = new HashMap<>();        Map<Object, Object> maps;        List<Map<Object, Object>> integers = new ArrayList<>();        for (Object[] obj : objects) {            if (obj[0].toString().startsWith("pay.alipay") || obj[0].equals("ALIPAY")) {                map.put("aliCount", "123");            } else if (obj[0].equals("WECHATPAY") || obj[0].toString().startsWith("pay.weixin") || obj[0].toString().startsWith("pay.wechat")) {                map.put("wxCount", "123");            } else if (obj[0].toString().startsWith("pay.bestpay")) {                map.put("wingCount", "123");            } else if (obj[0].toString().startsWith("pay.jdpay")) {                map.put("jdCount", "123");            } else if (obj[0].toString().startsWith("pay.qq")) {                map.put("qqCount", "123");            } else if (obj[0].toString().startsWith("pay.shiming")) {                map.put("smCount", "123");            } else if (obj[0].toString().startsWith("pay.unionpay") || obj[0].equals("UNIONPAY")) {                map.put("unionCount", "123");            } else if (obj[0].equals("CASH") || obj[0].equals("ALIPAY_CASH") || obj[0].equals("WECHATPAY_CASH")) {                map.put("cashCount", "123");            } else if (obj[0].equals("MEMBER")) {                map.put("memberCount", "123");            }        }        integers.add(map);        for (Map<Object, Object> map1 : integers) {            Set<Object> set = map1.keySet();            for (Object in : set) {                maps = new HashMap<>();                if (in.toString().equals("aliCount")) {                    maps.put("channel", "alipayAmount");                    maps.put("count", adminPayBill.getAliCount());                    maps.put("amount", adminPayBill.getAlipayAmount());                    jsonData.add(maps);                } else if (in.toString().equals("wxCount")) {                    maps.put("channel", "wechatAmount");                    maps.put("count", adminPayBill.getWxCount());                    maps.put("amount", adminPayBill.getWechatAmount());                    jsonData.add(maps);                } else if (in.toString().equals("wingCount")) {                    maps.put("channel", "wingPayAmount");                    maps.put("count", adminPayBill.getWingCount());                    maps.put("amount", adminPayBill.getWingPayAmount());                    jsonData.add(maps);                } else if (in.toString().equals("jdCount")) {                    maps.put("channel", "jdMicroPay");                    maps.put("count", adminPayBill.getJdCount());                    maps.put("amount", adminPayBill.getJdMicroPayAmount());                    jsonData.add(maps);                } else if (in.toString().equals("qqCount")) {                    maps.put("channel", "qqMicroPay");                    maps.put("count", adminPayBill.getQqCount());                    maps.put("amount", adminPayBill.getQqMicroPayAmount());                    jsonData.add(maps);                } else if (in.toString().equals("smCount")) {                    maps.put("channel", "smMicroPay");                    maps.put("count", adminPayBill.getSmCount());                    maps.put("amount", adminPayBill.getSmMicroPayAmount());                    jsonData.add(maps);                } else if (in.toString().equals("unionCount")) {                    maps.put("channel", "unionPay");                    maps.put("count", adminPayBill.getUnionCount());                    maps.put("amount", adminPayBill.getUnionPayAmount());                    jsonData.add(maps);                } else if (in.toString().equals("cashCount")) {                    maps.put("channel", "cashAmount");                    maps.put("count", adminPayBill.getCashCount());                    maps.put("amount", adminPayBill.getCashAmount());                    jsonData.add(maps);                } else if (in.toString().equals("memberCount")) {                    maps.put("channel", "MEMBER");                    maps.put("count", adminPayBill.getMemberCount());                    maps.put("amount", adminPayBill.getMemberAmount());                    jsonData.add(maps);                }            }        }        try {            return jsonObject.put("adminPayBill", jsonData).toString();        } catch (JSONException e) {            e.printStackTrace();            return null;        }    }    public List<OrderStatus> getOrderStatus() {        List<OrderStatus> orderStatuses = new ArrayList<>();        orderStatuses.add(OrderStatus.CANCELED);        orderStatuses.add(OrderStatus.FAIL);        orderStatuses.add(OrderStatus.INIT);        orderStatuses.add(OrderStatus.NOTSURE);        orderStatuses.add(OrderStatus.UNSETTLED);        orderStatuses.add(OrderStatus.REFUNDED);        return orderStatuses;    }}